package com.hollycrm.hollysqm.analyzer.util;

import lombok.extern.log4j.Log4j;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;

import static com.hollycrm.hollysqm.analyzer.util.Constant.*;

/**
 * Created by zhaihw on 2016/5/4.
 * jdbc工具
 */
@Log4j
public enum JdbcUtil {
    INSTANCE; //实例

    /**
     * 获取数据库连接
     *
     * @return 连接对象
     */
    public Connection getConnection() throws SQLException,ClassNotFoundException{
        String url = ConfigUtil.getProp(jdbcUrl);
        String driver = ConfigUtil.getProp(jdbcDriver);
        String user = ConfigUtil.getProp(jdbcUser);
        String pass = ConfigUtil.getProp(jdbcPwd);
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, pass);
        return conn;
    }

    /**
     * 执行查询
     *
     * @param sql      sql语句
     * @param params   参数
     * @param callback 回调函数
     * @param <T>      查询泛型
     * @return 对象
     */
    public <T> T executeQuery(String sql, Object[] params, JdbcCallback<T> callback) throws SQLException,ClassNotFoundException {
        log.info("executeQuery" + sql);
        Connection conn = null;
        try {
            conn = getConnection();
            return executeQuery(conn, sql, params, callback);
        } catch (SQLException e) {
            log.error("queryError", e);
            throw e;
        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                log.warn("关闭jdbc连接出错", e);
            }
        }
    }

    /**
     * 保持一个长连接的查询
     * @param conn 连接
     * @param sql sql
     * @param params       参数
     * @param callback 回调
     * @param <T> 对象类型
     * @return 对象
     * @throws SQLException sql异常
     * @throws ClassNotFoundException 驱动类异常
     */
    public <T> T executeQuery(Connection conn, String sql, Object[] params, JdbcCallback<T> callback) throws SQLException,ClassNotFoundException{
        log.info("executeQuery conn " + sql);
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            stat = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 1; i <= params.length; i++) {
                    stat.setObject(i, params[i - 1]);
                }
            }
            rs = stat.executeQuery();
            return callback.process(rs);
        } catch (SQLException e) {
            log.error("queryError", e);
            throw e;
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stat != null)
                    stat.close();
            } catch (SQLException e) {
                log.warn("关闭jdbc出错", e);
            }
        }
    }
}


